<template>
	<div class="add-subsidy-box">
		<el-form :model="formData" label-width="120px" :rules="rules" class="form-inline" ref="formData">
			<el-form-item class="form-item" label="执行城市" prop="city_id">
				<el-select v-model="formData.city_id" placeholder="城市" :disabled="infoDisabled" @change="changeCity">
					<el-option v-for="item in cityList" :key="item.id" :label="item.city_name" :value="item.id"></el-option>
				</el-select>
			</el-form-item>

			<el-form-item class="form-item" label="执行商圈" prop="area_id">
				<el-select
					v-model="formData.area_id"
					filterable
					placeholder="商圈"
					:disabled="infoDisabled"
					@change="changeArea"
				>
					<el-option v-for="item in areaList" :key="item.id" :label="item.area_name" :value="item.id"></el-option>
				</el-select>
			</el-form-item>

			<el-form-item class="form-item" label="执行店铺" prop="shop_id" v-if="identity == 'shop'">
				<el-select
					v-model="formData.shop_id"
					filterable
					placeholder="店铺名称"
					:disabled="infoDisabled"
					@change="changeShop"
				>
					<el-option v-for="item in shopList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
				</el-select>
			</el-form-item>

			<el-form-item class="form-item" label="行业" prop="industry">
				<el-select v-model="formData.industry" placeholder="行业" :disabled="infoDisabled" @change="changeIndustry()">
					<el-option
						v-for="item in industryJobList"
						:key="item.id"
						:label="item.label_name"
						:value="item.id"
					></el-option>
				</el-select>
			</el-form-item>

			<el-form-item class="form-item" label="岗位" prop="label_id">
				<el-select v-model="formData.label_id" placeholder="岗位名称" :disabled="infoDisabled" @change="priceChange">
					<el-option v-for="item in jobList" :key="item.id" :label="item.label_name" :value="item.id"></el-option>
				</el-select>
			</el-form-item>

			<el-form-item class="form-item" label="补贴名称" prop="name">
				<el-input
					@change="removeAllSpace"
					:disabled="infoDisabled"
					type="input"
					v-model="formData.name"
					class="w_300"
					placeholder="补贴名称"
					maxlength="20"
				></el-input>
			</el-form-item>
			<el-form-item class="form-item" label="活动开始日期" prop="start_time">
				<el-date-picker
					:picker-options="pickerOptions"
					:disabled="infoDisabled"
					v-model="formData.start_time"
					type="date"
					value-format="yyyy-MM-dd"
					format="yyyy-MM-dd"
					placeholder="活动开始日期"
				></el-date-picker>
				<span class="text-danger">*该日期是指订单的开始日期，不是下单日期</span>
			</el-form-item>
			<el-form-item class="form-item" label="活动结束日期" prop="end_time">
				<el-date-picker
					:picker-options="pickerOptions"
					:disabled="infoDisabled"
					v-model="formData.end_time"
					type="date"
					value-format="yyyy-MM-dd"
					format="yyyy-MM-dd"
					placeholder="活动结束日期"
				></el-date-picker>
			</el-form-item>

			<div class="form-item flex mb_40">
				<div class="key-label"><span class="text-danger">*</span>补贴商家</div>
				<div>
					<div class="rule-list">
						<div class="rule-item">
							<div class="rule-item-label">黄金</div>
							<div class="rule-item-label font-30">—</div>
							<el-input
								:disabled="disabledInput"
								placeholder="请输入"
								class="w_100"
								v-model="formData.level30"
								@input="checkPrice('30')"
							></el-input>
							<div class="rule-item-text">元/小时</div>
						</div>
						<div class="rule-prompt pl_20 mb_10" v-if="(formData.level30 && !promptDisabled)">
							<span v-if="shopPriceData.code == '601'"> {{ shopPriceData.msg }} </span>
							<span v-else> {{ promptPrice.level30 }} </span>
						</div>
					</div>
					<div class="rule-list">
						<div class="rule-item">
							<div class="rule-item-label">白银</div>
							<div class="rule-item-label font-30">—</div>
							<el-input
								:disabled="disabledInput"
								placeholder="请输入"
								class="w_100"
								v-model="formData.level20"
								@input="checkPrice('20')"
							></el-input>

							<div class="rule-item-text">元/小时</div>
						</div>
						<div class="rule-prompt pl_20 mb_10" v-if="(formData.level20 && !promptDisabled)">
							<span v-if="shopPriceData.code == '601'"> {{ shopPriceData.msg }} </span>
							<span v-else> {{ promptPrice.level20 }} </span>
						</div>
					</div>
					<div class="rule-list">
						<div class="rule-item">
							<div class="rule-item-label">青铜</div>
							<div class="rule-item-label font-30">—</div>
							<el-input
								:disabled="disabledInput"
								placeholder="请输入"
								class="w_100"
								v-model="formData.level10"
								@input="checkPrice('10')"
							></el-input>
							<div class="rule-item-text">元/小时</div>
						</div>
						<div class="rule-prompt pl_20 mb_10" v-if="(formData.level10 && !promptDisabled)">
							<span v-if="shopPriceData.code == '601'"> {{ shopPriceData.msg }} </span>
							<span v-else> {{ promptPrice.level10 }} </span>
						</div>
					</div>
				</div>
			</div>
			<!-- v-if="roleType == 1" -->
			<el-form-item class="form-item" label="成本承担方" prop="undertaker">
				<el-radio v-model="formData.undertaker" :disabled="infoDisabled" label="2">代理商</el-radio>
				<el-radio v-model="formData.undertaker" :disabled="platformDisabled" label="1">平台</el-radio>
			</el-form-item>

			<el-form-item class="form-item" label="备注">
				<el-input
					:disabled="infoDisabled"
					@change="remarkChange"
					type="textarea"
					v-model="formData.remark"
					style="width: 300px;"
					maxlength="250"
					show-word-limit
				></el-input>
			</el-form-item>
			<el-form-item class="mt_30">
				<el-button class="mr_30" @click="goBack()">返回</el-button>
				<el-button :disabled="infoDisabled" type="primary" @click="submitForm()">保存</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
import { fetchIndustryJob } from '@/api/label.js'
import { fetchAreaList, fetchShopList, fetPromptPriceList } from '@/api/shop.js'
import { fetchCityList } from '@/api/city.js'
import { subsidyShopInfo, subsidyAreaInfo } from '@/api/subsidy.js'
export default {
	name: 'subsidy-shop',
	data() {
		return {
			pickerOptions: {
				disabledDate(v) {
					return v.getTime() < new Date().getTime()
				}
			},
			// roleType: 2,
			roleType: JSON.parse(sessionStorage.getItem('manageInfo')).user_info.type,
			shopList: [],
			areaList: [],
			cityList: [],
			jobList: [],
			industryJobList: [],
			formData: {
				shop_id: '',
				city_id: '',
				area_id: '',
				industry: '',
				label_id: '',
				name: '',
				start_time: '',
				end_time: '',
				level30: '', //黄金
				level20: '', //白银
				level10: '', //青铜
				undertaker: '',
				remark: ''
			},

			rules: {
				city_id: [{ required: true, message: '请选择执行城市', trigger: 'change' }],
				area_id: [{ required: true, message: '请选择商圈', trigger: 'change' }],
				shop_id: [{ required: true, message: '请选择店铺', trigger: 'change' }],
				industry: [{ required: true, message: '请选择所属行业', trigger: 'change' }],
				label_id: [{ required: true, message: '请选择岗位名称', trigger: 'change' }],
				type: [{ required: true, message: '请选择加价方式', trigger: 'change' }],
				name: [{ required: true, message: '请输入补贴名称', trigger: 'change' }],
				start_time: [{ required: true, message: '请选择加价开始日期', trigger: 'change' }],
				end_time: [{ required: true, message: '请选择加价结束日期', trigger: 'change' }],
				undertaker: [{ required: true, message: '请选择成本承担方', trigger: 'change' }]
			},

			//提示调整价格
			promptPrice: {
				level10: '', //青铜
				level20: '', //白银
				level30: '' //黄金
			},

			promptDisabled: false,
			disabledInput: true,
			infoDisabled: false,
			platformDisabled: false,

			shopPriceData: {} //获取价格提示
		}
	},

	props: {
		identity: {
			type: String,
			default: ''
		},
		id: {
			type: String | Number,
			default: ''
		}
	},

	watch: {
		'formData.level30': {
			handler: function () {
				if (!this.id) this.getPromptPriceList()
			}
		},
		'formData.level20': {
			handler: function () {
				if (!this.id) this.getPromptPriceList()
			}
		},
		'formData.level10': {
			handler: function () {
				if (!this.id) this.getPromptPriceList()
			}
		}
	},

	mounted() {
		// identity shop：代表店铺增加补贴  area: 商圈增加补贴
		this.getcityList()
		this.platformDisabled = this.roleType == 1 ? false : true

		if (this.id) {
			this.infoDisabled = true
			this.platformDisabled = true
			this.getInfo()
		} else {
			// 代理商、平台进入默认成本承担方
			console.log('身份：', `${this.roleType == 1 ? '平台' : '代理商'}`)
			this.formData.undertaker = this.roleType == 1 ? '1' : '2'
		}
	},

	methods: {
		async getInfo() {
			try {
				let res = ''
				if (this.identity == 'shop') {
					res = await subsidyShopInfo({ id: this.id })
				} else if (this.identity == 'area') {
					res = await subsidyAreaInfo({ id: this.id })
				}

				Object.keys(this.formData).forEach(key => {
					this.formData[key] = res[key]
				})
				this.formData.undertaker += ''
				this.formData.level10 = +(this.formData.level10 / 100).toFixed(2) + ''
				this.formData.level20 = +(this.formData.level20 / 100).toFixed(2) + ''
				this.formData.level30 = +(this.formData.level30 / 100).toFixed(2) + ''

				await this.listArea()
				await this.getShopList()
				await this.getIndustryJob()
				this.getPromptPriceList()

				if (!this.formData.industry) return (this.jobList = [])

				this.jobList = this.industryJobList.find(x => +x.id === +this.formData.industry).children
			} catch (err) {}
		},
		// 确认添加
		async submitForm() {
			// 表单检查
			let validate = await this.$refs.formData.validate().catch(err => err)
			if (!validate) return

			// 时间检查
			let verify = await this.compareDate(this.formData.start_time, this.formData.end_time)
			if (!verify) return

			// 价格检查
			const { level10, level20, level30 } = this.formData
			if (!level10 || !level20 || !level30) return this.$message.error('价格调整不能为空')
			if (level10 > 5 || level20 > 5 || level30 > 5) return this.$message.error('补贴金额区间为【0～5】元')
			if (level10 == 0 && level20 == 0 && level30 == 0) return this.$message.error('补贴金额异常，不可都是【0】元')

			// 不是店铺添加补贴要去除返回店铺id
			if (this.identity != 'shop') delete this.formData.shop_id

			this.$emit('sendValue', this.formData)
		},

		// 比较时间大小
		async compareDate(date1, date2) {
			if (new Date(date1).getTime() > new Date(date2).getTime()) {
				this.$message.error('开始时间不能大于结束时间')
				return false
			}
			return true
		},
		// onBasePriceBlur(type) {
		// if (this.formData['level' + type]) {
		// 	this.formData['level' + type] *= 1
		// }
		// },
		//价格监听
		async checkPrice(type) {
			let checkPlan = this.formData['level' + type] + ''

			// 第一位是（.）那么在第一位 补位 0
			if (checkPlan.substring(0, 1) == '.') checkPlan = '0' + checkPlan

			checkPlan = checkPlan
				.replace(/[^\d.]/g, '') // 清除“数字”和“.”以外的字符
				.replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
				.replace(/^\./g, '') // 保证第一个为数字而不是.
				.replace('.', '$#$')
				.replace(/\./g, '')
				.replace('$#$', '.')
				.replace(/^()*(\d+)\.(\d\d).*$/, '$1$2.$3')
			this.formData['level' + type] = checkPlan
		},

		//去除全部空格
		removeAllSpace() {
			this.formData.name = this.formData.name.replace(/\s+/g, '')
		},

		//去除全部空格
		remarkChange() {
			this.formData.remark = this.formData.remark.replace(/\s+/g, '')
		},

		//查询价格提示
		async getPromptPriceList() {
			try {
				const { city_id, area_id, industry, label_id, shop_id } = this.formData

				let result = this.shopList.filter(it => it.id == +shop_id)

				let ret = await fetPromptPriceList({
					city_id: city_id,
					area_id: area_id,
					shop_sn: result.length ? result[0].shop_sn : '',
					industry: industry,
					label_id: label_id,
					data_type: '',
					type: ''
				})

				this.shopPriceData = {
					code: ret.code,
					msg: ret.msg
				}

				ret.forEach(item => {
					let priceC = +(+item.staff_price / 100).toFixed(2)
					let priceB = +(+item.shop_price / 100 - +this.formData['level' + item.type]).toFixed(2)
					this.promptPrice[
						'level' + item.type
					] = `调整后劳动者 ${priceC} 元/小时，店铺 ${priceB} 元/小时 (单独定价的除外)`
				})
			} catch (err) {
				console.log(err)
			}
		},

		//价格是否能编辑
		priceChange() {
			const { city_id, area_id, industry, label_id } = this.formData
			if (city_id && area_id.toString() && industry && label_id) {
				this.disabledInput = false
				this.promptDisabled = false
				this.getPromptPriceList()
			} else {
				this.disabledInput = true
				this.promptDisabled = true
			}
		},

		// 返回
		goBack() {
			this.$router.go(-1)
		},

		//店铺列表
		async getShopList() {
			try {
				let ret = await fetchShopList({
					sign_status: 30, //已合作的店铺
					status: 1, //启用的店铺
					city_id: this.formData.city_id,
					area_id: this.formData.area_id == 0 ? '' : this.formData.area_id
				})
				ret.list.forEach(it => {
					it.id = +it.id
				})
				this.shopList = ret.list
			} catch (err) {
				console.log(err)
			}
		},

		// 获取城市列表
		async getcityList() {
			try {
				let ret = await fetchCityList()
				this.cityList = ret.list
			} catch (err) {
				console.log('err:', err)
			}
		},

		//获取商圈列表
		async listArea() {
			try {
				let ret = await fetchAreaList({
					city_id: this.formData.city_id
				})

				let area = ret.list.filter(x => {
					return x.id != 0
				})

				if (this.identity == 'area') {
					area.unshift({ id: 0, area_name: '全部' })
				}

				this.areaList = area
			} catch (error) {
				console.log('error:', error)
			}
		},

		// 城市监听
		changeCity() {
			for (let key in this.formData) {
				if (key != 'city_id' && key != 'undertaker') this.formData[key] = ''
			}
			this.jobList = []
			this.industryJobList = []
			this.shopList = []

			if (!this.formData.city_id) return
			this.listArea()
			if (this.identity == 'area') this.getIndustryJob()
		},

		// 商圈监听
		changeArea() {
			if (this.identity == 'shop') {
				//补贴店铺
				this.industryJobList = []
				this.jobList = []
				this.formData.industry = ''
				this.formData.label_id = ''
				this.formData.shop_id = ''
				this.getShopList()
			} else if (this.identity == 'area') {
				//补贴商圈
			}
		},

		// 店铺监听
		changeShop() {
			this.getIndustryJob()
			this.formData.industry = ''
			this.formData.label_id = ''
		},

		// 获取行业
		async getIndustryJob() {
			try {
				let result = this.shopList.filter(it => it.id == +this.formData.shop_id)

				let ret = await fetchIndustryJob({
					city_id: this.formData.city_id,
					shop_sn: result.length ? result[0].shop_sn : ''
				})
				this.industryJobList = ret
			} catch (err) {
				console.log(err)
			}
		},

		// 行业监听
		changeIndustry() {
			this.priceChange()

			this.formData.label_id = ''

			if (!this.formData.industry) return (this.jobList = [])

			this.jobList = this.industryJobList.find(x => +x.id === +this.formData.industry).children
		}
	}
}
</script>

<style lang="scss" scoped>
.box {
	padding: 0 10px 10px;
}

.text-danger {
	color: red;
}
.key-label {
	font-size: 12px;
	width: 120px;
	color: #606266;
	text-align: right;
	box-sizing: border-box;
	padding-right: 12px;
}
.rule-list {
	// border: 1px solid #ebebeb;
	border-radius: 4px;
	padding: 10px;
}
.rule-item {
	// width: 500px;
	display: flex;
	line-height: 30px;
	font-size: 12px;
	.rule-item-label {
		text-align: center;
		width: 75px;
		font-size: 16px;
		font-weight: bold;
	}
	.w_100 {
		margin: 0 10px 0 20px;
	}
	.rule-item-text {
		color: #999999;
	}
}
.rule-prompt {
	color: #d9001b;
	font-size: 12px;
}
.font-30 {
	font-size: 30px !important;
}
</style>

<style>
.add-subsidy-box .el-form-item__content {
	margin-bottom: 10px;
}
.add-subsidy-box .el-select {
	width: 300px !important;
}
.add-subsidy-box .el-date-editor.el-input {
	width: 300px !important;
}
</style>



// WEBPACK FOOTER //
// src/components/subsidy/components/SubsidyAdd.vue